#!/bin/bash

# 处理目录的函数
process_directory() {
  local project_dir=$1
  local dir_name=$2
  local need_cd_back=$3
  
  if [ -d "${project_dir}/${dir_name}" ]; then
    echo "处理 ${project_dir}/${dir_name}"
    
    # 进入目录
    cd "${project_dir}/${dir_name}"
    need_cd_back=true

    # 检查目录本身是否是git仓库
    if [ -d ".git" ]; then
      echo "处理目录本身: ${dir_name}"
      
      # 获取当前git仓库的URL和分支
      repo_url=$(git config --get remote.origin.url)
      branch_name=$(git rev-parse --abbrev-ref HEAD)
      
      echo "${dir_name}仓库URL: $repo_url"
      echo "${dir_name}分支: $branch_name"
      
      # 备份当前目录名称（以防万一）
      backup_dir="${dir_name}_backup_$(date +%Y%m%d_%H%M%S)"
      cd ..
      mv "${dir_name}" "$backup_dir"
      
      # 使用--depth=1重新克隆仓库
      echo "重新克隆${dir_name}仓库..."
      git clone "$repo_url" "${dir_name}" -b "$branch_name" --depth=1
      
      # 如果克隆成功，删除备份
      if [ $? -eq 0 ]; then
        echo "成功克隆${dir_name}仓库，删除备份"
        rm -rf "$backup_dir"
      else
        echo "克隆${dir_name}仓库失败，恢复备份"
        rm -rf "${dir_name}"
        mv "$backup_dir" "${dir_name}"
      fi
    else
      # 如果目录本身不是git仓库，则处理子目录
      echo "目录本身不是git仓库，处理子目录..."
      
      # 遍历目录下的所有子目录
      for subdir in */; do
        if [ -d "$subdir" ] && [ -d "$subdir/.git" ]; then
          echo "处理子目录: $subdir"
          
          # 获取当前git仓库的URL和分支
          cd "$subdir"
          repo_url=$(git config --get remote.origin.url)
          branch_name=$(git rev-parse --abbrev-ref HEAD)
          cd ../
          
          echo "${subdir%/}仓库URL: $repo_url"
          echo "${subdir%/}分支: $branch_name"
          
          # 备份当前目录名称（以防万一）
          backup_dir="${subdir%/}_backup_$(date +%Y%m%d_%H%M%S)"
          mv "$subdir" "$backup_dir"
          
          # 使用--depth=1重新克隆仓库
          echo "重新克隆${subdir%/}仓库..."
          git clone "$repo_url" "${subdir%/}" -b "$branch_name" --depth=1
          
          # 如果克隆成功，删除备份
          if [ $? -eq 0 ]; then
            echo "成功克隆${subdir%/}仓库，删除备份"
            rm -rf "$backup_dir"
          else
            echo "克隆${subdir%/}仓库失败，恢复备份"
            rm -rf "${subdir%/}"
            mv "$backup_dir" "${subdir%/}"
          fi
        fi
      done
    fi
  fi
  
  echo "$need_cd_back"
}

# 遍历包含sync的目录
find . -maxdepth 1 -type d -name "*sync*" | while read project_dir; do
  project_dir=${project_dir#./}
  echo "处理项目: $project_dir"
  
  # 标记是否需要返回上一级
  need_cd_back=false
  
  # 处理feiyu目录
  need_cd_back=$(process_directory "$project_dir" "feiyu" "$need_cd_back")
  
  # 处理system目录
  need_cd_back=$(process_directory "$project_dir" "system" "$need_cd_back")
  
  # 只有在实际进入子目录时才返回上一级
  if [ "$need_cd_back" = true ]; then
    cd ..
  fi
done

echo "所有项目处理完成！"
